# @author zoulei
# 用于测试达梦 ODBC 直连及中文字段显示
import pyodbc

# 配置参数
driver = "DM8 ODBC DRIVER"  # 必须与 ODBC 管理器中显示的驱动名称一致
server = "<your_host>:<your_port>"
uid = "<your_uid>"
pwd = "<your_pwd>"
# database = ""  # 如有需要可加

# 构造连接字符串
conn_str = (
    f"DRIVER={{{driver}}};"
    f"SERVER={server};"
    f"UID={uid};"
    f"PWD={pwd};"
    "ServerType=8;"
    "Protocol=TCP;"
    # f"DATABASE={database};"  # 如有需要可取消注释
)

print("Testing ODBC Direct Connection...")
print("Connection String:", conn_str)

try:
    conn = pyodbc.connect(conn_str, autocommit=True)
    print("SUCCESS: ODBC Connection Established!")

    sql = "SELECT * FROM b01 FETCH FIRST 10 ROWS ONLY"
    cursor = conn.cursor()
    cursor.execute(sql)

    # 获取字段名
    field_names = [desc[0] for desc in cursor.description]

    # 输出到文件，保证UTF-8编码
    output_file = "output.txt"
    with open(output_file, "w", encoding="utf-8") as f:
        f.write("字段名: " + ", ".join(field_names) + "\n")
        for row in cursor.fetchall():
            row_str = ", ".join([str(item) if item is not None else "" for item in row])
            f.write("数据: " + row_str + "\n")

    conn.close()
    print("Connection Closed")
    print("请用支持UTF-8的编辑器（如VSCode、Notepad++）打开 output.txt 查看字段名和数据")
except Exception as e:
    print("ERROR: ODBC Connection Failed")
    print(str(e))

print("Test Complete") 